package com.cat.dataStructure02;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/count-collisions-on-a-road/description/
 * @create 2025/10/14 21:06
 * @since JDK17
 */

public class Solution19 {
    public int countCollisions(String directions) {
        int ans = 0, n = directions.length(), top = 0;
        char[] s = directions.toCharArray(), stack = new char[n];
        for (int i = 0; i < n; i++) {
            if (s[i] == 'L') {
                if (top > 0 && stack[top - 1] != 'L') { // 会发生碰撞
                    ans += stack[top - 1] == 'R' ? 2 : 1;
                    stack[top - 1] = 'S';
                } else { // 不会
                    stack[top++] = s[i];
                }
            } else {
                stack[top++] = s[i];
            }
        }
        int k = 0;
        for (int i = 0; i < top; i++) {
            if (stack[i] == 'R') {
                k++;
            } else {
                ans += k;
                k = 0;
            }
        }

        return ans;
    }
}
